# crud/sys_api_teamwork.py
from sqlalchemy.orm import Session
from src.models.sys_api_teamwork import SysApiTeamwork
from src.schemas.sys_api_teamwork import SysApiTeamworkCreate, SysApiTeamworkUpdate


def create_api_teamwork(db: Session, api_teamwork: SysApiTeamworkCreate):
    """
    创建单条 API 项目协同记录。
    """
    db_api_teamwork = SysApiTeamwork(**api_teamwork.dict())
    db.add(db_api_teamwork)
    db.commit()
    db.refresh(db_api_teamwork)
    return db_api_teamwork


def create_api_teamworks(db: Session, api_teamworks: list[SysApiTeamworkCreate]):
    """
    批量创建 API 项目协同记录。
    """
    db_api_teamworks = [SysApiTeamwork(**at.dict()) for at in api_teamworks]
    try:
        db.add_all(db_api_teamworks)
        db.commit()
        for db_api_teamwork in db_api_teamworks:
            db.refresh(db_api_teamwork)
        return db_api_teamworks
    except Exception as e:
        db.rollback()
        raise e


def get_api_teamwork(db: Session, teamwork_id: str):
    """
    根据 ID 获取 API 项目协同记录。
    """
    return db.query(SysApiTeamwork).filter(SysApiTeamwork.id == teamwork_id).first()


def get_api_teamworks(db: Session, skip: int = 0, limit: int = 100):
    """
    获取 API 项目协同记录列表。
    """
    return db.query(SysApiTeamwork).offset(skip).limit(limit).all()


def update_api_teamwork(db: Session, teamwork_id: str, api_teamwork: SysApiTeamworkUpdate):
    """
    更新 API 项目协同记录。
    """
    db_api_teamwork = db.query(SysApiTeamwork).filter(SysApiTeamwork.id == teamwork_id).first()
    if db_api_teamwork is None:
        return None
    update_data = api_teamwork.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_api_teamwork, key, value)
    db.commit()
    db.refresh(db_api_teamwork)
    return db_api_teamwork


def delete_api_teamwork(db: Session, teamwork_id: str):
    """
    删除 API 项目协同记录。
    """
    db_api_teamwork = db.query(SysApiTeamwork).filter(SysApiTeamwork.id == teamwork_id).first()
    if db_api_teamwork is None:
        return None
    db.delete(db_api_teamwork)
    db.commit()
    return db_api_teamwork
